import 'dart:async';

import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';


import '../../AppConfig/Config.dart';
import '../../AppConfig/RouteAct.dart';
import '../../AppConfig/StringEncapsulation.dart';
import '../../http/NoLoadingPostApi.dart';
import '../../http/api.dart';
import '../../l10n/messages.dart';
import 'SetPaymentPassword.dart';

class PayAuthentication extends StatefulWidget {
  const PayAuthentication({super.key, required this.phoneNum});
  final String phoneNum;
  @override
  State<PayAuthentication> createState() => _PayAuthenticationState();
}

class _PayAuthenticationState extends State<PayAuthentication> {
  String smsCode="";
  late Timer _timer;
  int curentTimer=60;
  String validCodeReqNo="";
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _timer =Timer.periodic(Duration(milliseconds: 1000), (timer) {
      curentTimer--;
      if (curentTimer ==0){
        _timer.cancel();

      }
      setState(() {

      });
    });
    getSMSCode();

  }
  void startTime(){
    setState(() {
      curentTimer = 60;
// 设置定时器正在运行
      _timer = Timer.periodic(Duration(seconds: 1), (timer) {
        curentTimer--;
        if (curentTimer == 0) {
          _timer.cancel();
        ; // 定时器结束后设置为非运行状态
          print("Timer ended");

          if (mounted) {
            setState(() {}); // 刷新状态以使按钮可点击
          }
        }
        if (!mounted) {
          _timer.cancel(); // 防止在组件被销毁后仍然运行定时器
        }
        setState(() {});
      });
    });
  }
  void getSMSCode(){
    ApiManager.postData(
      context,
      'api/auth/sms/sendPhoneValidCode',
      {
        "phone": widget.phoneNum,
        "clientType": "DRIVER",
        "codeType": "PAY_PASS"
      },
          (responseData)  {
            validCodeReqNo=responseData['data']['validCodeReqNo'];
      },
    );
  }
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _timer.cancel();

  }
  @override
  Widget build(BuildContext context) {
    var messages = AppLocalizations.of(context)!;
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        backgroundColor: Colors.white,
        centerTitle: true,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios, color: Colors.black),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: Text("身份验证",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w300,fontSize: 16.sp),),
      ),
      body:  Column(
        children: [
          Expanded(child: ListView(
            children: [
              Container(
                margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w),
                padding: EdgeInsets.only(top: 14.h,left: 10.w,right: 10.w,bottom: 8.h),
                decoration: BoxDecoration(
                  color:Colors.white,
                  borderRadius: BorderRadius.all(Radius.circular(10)),
                ),
                child: Column(
                  children: [
                    Row(
                      children: [
                        Text("手机号",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                        SizedBox(width: 10.w,),
                        Text(maskPhoneNumber(widget.phoneNum),style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                      ],
                    ),
                    SizedBox(height: 14.h,),
                    Container(
                      height: 1.h,
                      color: MyColors.backgreyColor,
                    ),
                    SizedBox(height: 14.h,),
                    Row(
                      children: [
                        Text("验证码",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                        SizedBox(width: 10.w,),
                        Container(
                          width: screenSize.width-200.w,
                          height: 35.h,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Container(
                                width:100.w,
                                child:TextField(
                                  decoration: InputDecoration(
                                    hintText: '填写验证码',
                                    hintStyle:TextStyle(fontSize: 14.sp,color: MyColors.hintColor),
                                    filled: true,
                                    fillColor:Colors.white,
                                    border: InputBorder.none,
                                    alignLabelWithHint: true,
                                    // contentPadding: EdgeInsets.symmetric(vertical: 6.0.h, horizontal: 0.0.w),
                                  ),
                                  keyboardType: TextInputType.number,
                                  textAlign: TextAlign.left,
                                  style: TextStyle(color: Colors.black),
                                  onChanged: (value) {
                                    setState(() {
                                      smsCode=value;
                                    });
                                  },
                                ),
                              ),


                            ],
                          ),
                        ),
                        Container(
                          height: 25.h ,
                          width:100.w,
                          // margin: EdgeInsets.only(left: 30.w,right: 30.w),
                          decoration: BoxDecoration(
                              color: curentTimer > 0?Color.fromRGBO(223, 223, 223, 1):Color.fromRGBO(231, 112, 27, 0.85),
                              borderRadius: BorderRadius.all(Radius.circular(30))),

                          child: Center(
                            child: GestureDetector(
                              child: curentTimer > 0?Text(curentTimer.toString() +"s",style: TextStyle(color: Colors.white,fontSize: 14.sp),)
                                  :Text("重新发送",style: TextStyle(color: Colors.white,fontSize: 14.sp),),
                              onTap: (){
                                setState(() {
                            if(curentTimer==0) {
                              startTime();
                              getSMSCode();
                              curentTimer = 60;
                              _timer = Timer.periodic(
                                  Duration(milliseconds: 1000), (timer) {
                                curentTimer--;
                                if (curentTimer == 0) {
                                  _timer.cancel();
                                  print(widget.phoneNum);
                                }
                              });
                            }
                                });

                              },
                            ),
                          ),


                        ),
                      ],
                    )
                  ],
                ),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  TextButton(onPressed: (){
                    showModalBottomSheet(context: context, builder: (BuildContext context)
                    {
                      return Container(
                        height: 280.h,
                        decoration: BoxDecoration(
                            color:Colors.white,
                            borderRadius: BorderRadius.all(Radius.circular(10))),
                        padding: EdgeInsets.only(top: 18.h,left: 15.w,right: 15.w,bottom: 65.h),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text("收不到验证码？",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w600),),
                                GestureDetector(
                                  child: Icon(Icons.close,color: MyColors.textColor,),
                                  onTap: (){
                                    Navigator.pop(context);
                                  },
                                ),
                              ],
                            ),
                            SizedBox(height: 10.h,),
                            Text("验证码将由平台发送到您的手机号上",style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
                            SizedBox(height: 10.h,),
                            Text("1.如收不到验证码，请确认手机号是否为平台预留手机号码，如非平台预留手机号，请联系平台客服咨询。",style: TextStyle(color:Colors.black,fontSize: 13.sp),),
                            SizedBox(height: 4.h,),
                            Text("2.如预留手机号已停用，请联系平台客服处理。",style: TextStyle(color:Colors.black,fontSize: 13.sp),),
                            SizedBox(height: 4.h,),
                            Text("3.请检查短信是否被手机安全软件拦截。",style: TextStyle(color:Colors.black,fontSize: 13.sp),),
                          ],
                        ),
                      );
                    });
                  }, child: Text("收不到验证码?",style: TextStyle(color: MyColors.themeColor,fontSize: 13.sp),)),
                ],
              ),

            ],
          ),
          ),
          Container(
            height: 80.h,
            color: Colors.white,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                    height: 40.h ,
                    margin: EdgeInsets.only(left: 30.w,right: 30.w),
                    decoration: BoxDecoration(
                        color:MyColors.themeColor,
                        borderRadius: BorderRadius.all(Radius.circular(30))),

                    width: double.infinity,


                    child: TextButton(
                      child: Text(messages["下一步"],style: TextStyle(color: Colors.white,fontSize: 14.sp,fontWeight: FontWeight.w600),),

                      onPressed: (){
                        if(smsCode==""){
                          BrnToast.show("请输入验证码", context,);
                        }else{
                          ApiManager.postData(
                            context,
                            'api/auth/sms/checkPhoneValidCode',
                            {
                              "phone": widget.phoneNum,
                              "clientType": "DRIVER",
                              "codeType": "PAY_PASS",
                              "validCode": smsCode,
                              "validCodeReqNo": validCodeReqNo,
                            },
                                (responseData)  {
                                  Navigator.push( context, FadeRoute(page:SetPaymentPassword()));
                            },
                          );
                        }


                      },
                    )
                ),
              ],
            ),
          ),
        ],
      ),

    );
  }
}

